
import java.net.*;
import java.io.*;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Samanthol
 */
public class ComunicaTCPServer {
    private ServerSocket sockServ;
    private int portServ;
    private Communica com;
    

    public Communica getCom() {
        return com;
    }

    public ComunicaTCPServer(int port) {
        this.portServ = port;
        try {
            System.out.println("In " + ComunicaTCPServer.class.getName() + " : Creating the server socket on " + portServ);
            this.sockServ = new ServerSocket(portServ);

            while (true) {
                Socket sockfd = this.sockServ.accept();
                System.out.println("The server " + ComunicaTCPServer.class.getName() + " accepted a client");
                InputStreamReader inReader = new InputStreamReader(sockfd.getInputStream());
                OutputStreamWriter outWriter = new OutputStreamWriter(sockfd.getOutputStream());
                BufferedReader br = new BufferedReader(inReader);
                BufferedWriter bw = new BufferedWriter(outWriter);

                System.out.println("In " + ComunicaTCPServer.class.getName() + " : Retrieved the inputStream & outputStream");
                
                com = new Communica(bw, br);
                com.setDefaultCloseOperation(Communica.EXIT_ON_CLOSE);
            }
        } catch (IOException ex) {
            System.err.println("Your error is in : " + ComunicaTCPServer.class.getName().toString() + " : " + ex.getMessage());
        }
    
        
    }

    public void run() {
        try {
            System.out.println("In " + ComunicaTCPServer.class.getName() + " : Creating the server socket on " + portServ);
            this.sockServ = new ServerSocket(portServ);

            while (true) {
                Socket sockfd = this.sockServ.accept();
                System.out.println("The server " + ComunicaTCPServer.class.getName() + " accepted a client");
                InputStreamReader inReader = new InputStreamReader(sockfd.getInputStream());
                OutputStreamWriter outWriter = new OutputStreamWriter(sockfd.getOutputStream());
                BufferedReader br = new BufferedReader(inReader);
                BufferedWriter bw = new BufferedWriter(outWriter);

                System.out.println("In " + ComunicaTCPServer.class.getName() + " : Retrieved the inputStream & outputStream");
                
                com = new Communica(bw, br);
                com.setDefaultCloseOperation(Communica.EXIT_ON_CLOSE);
            }
        } catch (IOException ex) {
            System.err.println("Your error is in : " + ComunicaTCPServer.class.getName().toString() + " : " + ex.getMessage());
        }
    }
    
}
